package cn.tom.config.customize;


import cn.tom.entity.XUser;
import cn.tom.tools.JwtUtil;
import cn.tom.tools.XResp;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 酒辞
 * 校验成功
 */

@Component
@Slf4j
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        XUser user = (XUser) authentication.getPrincipal();
        String token = JwtUtil.createUidToken(user.getId());
        response.setContentType("application/json;charset=UTF-8");
        if (token == null){
            Map<String, Object> packMap = XResp.packM(500, "登陆失败，请重新登陆", "");
            response.setStatus(401);
            response.getWriter().write(objectMapper.writeValueAsString(packMap));
        }

        String tokenKey ="token:" + token;
        Map<String ,Object> map=new HashMap<>();
        map.put("code",200);
        map.put("msg","登录成功");
        map.put("token",token);
        long expireTime = 120 * 60 * 1000;
        redisTemplate.opsForValue().set(tokenKey,token,expireTime,TimeUnit.SECONDS);
        ObjectMapper objectMapper=new ObjectMapper();
        String json=objectMapper.writeValueAsString(map);
        response.setStatus(200);
        response.getWriter().println(json);
        response.flushBuffer();








    }
}
